<?php declare(strict_types = 1);

namespace Initiating\Message;

use Initiating\Contract\ITxTransaction;
use Communication\TxSocketData;

/**
 * 未使用 使用需要安装 PHP-Amqp 库
 * @author mg
 *
 */
class ReceiveMessage
{
	/**
	 * 
	 * @var \AMQPConnection
	 */
	private $connection;
	
	/**
	 * 
	 * @var \AMQPChannel
	 */
	private $channel;
	
	public function getChannel(): \AMQPChannel {
		return $this->channel;
	}
	
	public function getConnection(): \AMQPConnection {
		return $this->connection;
	}
	
	/**
	 * 
	 * @var ReceiveMessage
	 */
	private static $intance;
	
	
	private $routeArray = [];
	
	private function __construct()
	{
		
		$conf=[
				'host'=>'127.0.0.1',
				'port'=>'5672',
				'login'=>'guest',
				'password'=>'guest',
				'vhost'=>'/'
		];
		$this->connection = new \AMQPConnection($conf);
	}
	
	/**
	 * 
	 * @param array $conf
	 * @return self
	 */
	public static function getInstance(): self
	{
		if (static::$intance instanceof self) {
			return static::$intance;
		}
		
		static::$intance = new static();
		
		return static::$intance;
	}
	
	/**
	 * @param ITxTransaction $tanstation
	 * @param string $routeKey
	 * @param int $coroutineId
	 * @throws \ErrorException
	 */
	public function received(ITxTransaction $tanstation, string $routeKey, int $coroutineId)
	{
		if (isset($this->routeArray[$routeKey])) {
			// 已启动
			return ;
		}
		
		if(!$this->connection->connect()){
			throw new \ErrorException('connetc error');
		}
		$channel=new \AMQPChannel($this->connection);
		
		
		$exchange=new \AMQPExchange($channel);
		
		$exchange->setName('amq.topic');
		$exchange->setType(AMQP_EX_TYPE_FANOUT);
		//echo "Exchange Status:".$exchange->declare()."\n";
		
		$queue = new \AMQPQueue($channel);
		$queue->setName('zblQueue');
		$queue->setFlags(AMQP_DURABLE); //持久化
		echo "Message Total:".$queue->declare()."\n";
		echo 'Queue Bind: '.$queue->bind('amq.topic', $routeKey)."\n";
		echo "Message:\n";
		
		$this->routeArray[$routeKey] = $routeKey;
		
		$queue->consume(function(\AMQPEnvelope $envelope, \AMQPQueue $queue)use ($tanstation, $coroutineId){
			
			$msg = $envelope->getBody();
			$tanstation->waitForReceiveData(TxSocketData::fromMsg($msg), $coroutineId);
			
			$queue->ack($envelope->getDeliveryTag());
			
// 			$queue->getChannel()->close();
			
// 			$queue->getConnection()->disconnect();
			
		});
			
	}
	
// 	public function __destruct()
// 	{
// 		$this->routeArray = [];
		
// 		$this->channel->close();
		
// 		$this->connection->disconnect();
// 	}
}